<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

class DynaFormController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle('表单管理');
		$this->setActionTitle(array(
				'index' => '表单列表',
				'add' => '添加表单',
				'modify' => '修改表单',
				'recycle' => '回收站' 
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle' 
		));
	}
	
	public function indexAction() {
		$this->getLists( 0 );
	}
	
	public function recycleAction() {
		$this->getLists( 1 );
	}
	
	// 获取列表
	private function getLists($is_deleted) {
		$condition = array(
			'a.is_deleted' => $is_deleted,
			'b.partner' => $this->aid,
		);
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$dynaFormLists = M('DynaForm a')->join('__CUSTOMER__ b on a.cid = b.id', 'LEFT')->where($condition)->field('a.*,b.name as customerName,b.email as customerEmail,b.tel')->limit($pagesize)->page($page)->order('a.id')->select();
		$count = M('DynaForm')->join('Customer b on a.cid = b.id')->where($condition)->count();
		$this->assign('dynaFormLists', $dynaFormLists);
		$this->showPage($count, $pagesize);
		$this->display();
	}
	
	public function addAction() {
		$this->display('save');
	}
	
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$condition = array(
			'a.id' => $id,
			'b.partner' => $this->aid,
		);
		$d = D("DynaForm")->alias("a");
		$dynaForm = $d->join('__CUSTOMER__ b on a.cid = b.id', 'LEFT')->where($condition)->field("a.*,b.email as customerEmail")->find();
		$dynaForm and $dynaForm['config'] = $d->parseArray(unserialize($dynaForm['config']));
		$this->assign("dynaForm", $dynaForm);
		$this->display('save');
	}
	
	// 提交修改
	public function saveAction() {
		$model = D("DynaForm");
		if ($model->create()) {
			if (empty($_REQUEST['id'])) {
				unset($model->id);
				if ($model->add()) {
					$this->ajaxSuccess("添加成功！");
				} else {
					$this->ajaxError("添加失败！");
				}
			} else {
				if (false !== $model->save()) {
					$this->ajaxSuccess("修改成功！");
				} else {
					$this->ajaxError("修改失败！");
				}
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
	/**
	 * 获得当前合作商的用户列表
	 */
	public function getUserListAction() {
		$name = I("name","");
		$customerLists = M("Customer")->where(array(
				'partner' => $this->aid,
				'_string' => "email like '%$name%' or name like '%$name%'"
		))->field("id,name,email")->limit(15)->select();
		$this->ajaxSuccess("", $customerLists);
	}
	
	// 恢复
	public function restoreAction() {
		$this->ajaxRestore();
	}
	
	// 移除
	public function removeAction() {
		$this->ajaxRemove();
	}
	
	// 设置状态
	public function setStatusAction() {
		$this->ajaxSetStatus();
	}
}

?>